package net.xxcl.kygl.controller;

import net.xxcl.kygl.pojo.Criteria;
import net.xxcl.kygl.pojo.Project;
import net.xxcl.kygl.pojo.Sbpsyj;
import net.xxcl.kygl.pojo.User;
import net.xxcl.kygl.service.ProjectService;
import net.xxcl.kygl.service.SbpsyjService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * User: 夏汛
 * Date: 12-5-28
 * Time: 下午11:47
 */
@Controller
@RequestMapping("/sbpsyj")
public class SbpsyjController {

    @Autowired
    private SbpsyjService sbpsyjService;
    @Autowired
    private ProjectService projectService;

    /**
     * 指派专家
     * @param expertids
     * @param projectid
     * @return
     */
    @RequestMapping(value = "/appointExperts",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> appointExperts(
                            @RequestParam(value = "expertids") String expertids,
                            @RequestParam(value = "projectid") Integer projectid){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        try{
            sbpsyjService.appointExperts(expertids,projectid);
            responseMap.put("success", "true");
            responseMap.put("info","指派成功");
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info","指派专家失败");
        }
        return responseMap;
    }

    /**
     * 获取专家审核立项课题分页
     * @param start
     * @param limit
     * @return
     */
    @RequestMapping(value = "/listForLxktps",method= RequestMethod.POST)
    public @ResponseBody
    Map<String,Object> listForLxktps(@RequestParam(value = "start") Integer start,
                                     @RequestParam(value = "limit") Integer limit,
                                     HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        User user = (User)request.getSession().getAttribute("user");
        criteria.put("sbpsyj_userid",user.getId());
        int total = sbpsyjService.countBySbpsyj(criteria);
        criteria.setMysqlOffset(start);
        criteria.setMysqlLength(limit);
        criteria.setOrderByClause("t_project.id desc");
        criteria.put("state",1);
        List<Project> list = sbpsyjService.selectBySbpsyj(criteria);
        for(Project project:list){
            List<Map> users = projectService.getUserByProjectId(project.getId());
            if(users.get(0).get("deptname")!=null){
                project.setDeptname((String) users.get(0).get("deptname"));
            }
            StringBuffer sb = new StringBuffer();
            for(Map map:users){
                if((Boolean)map.get("iscolleague")){
                    sb.append(","+map.get("username"));
                } else {
                    sb.append(",("+map.get("username")+")");
                }
            }
            project.setNames(sb.substring(1));
        }
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 提交评审意见
     * @param isagree
     * @param projectid
     * @return
     */
    @RequestMapping(value = "/submitPsyj",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> submitPsyj(
            @RequestParam(value = "isagree") Boolean isagree,@RequestParam(value = "projectid") Integer projectid,
            HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        try{
            User user = (User)request.getSession().getAttribute("user");
            Sbpsyj sbpsyj = new Sbpsyj();
            sbpsyj.setProjectid(projectid);
            sbpsyj.setUserid(user.getId());
            sbpsyj.setIsagree(isagree);
            sbpsyjService.updateByPrimaryKeySelective(sbpsyj);
            responseMap.put("success", "true");
            responseMap.put("info","意见已经提交");
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info","意见提交失败");
        }
        return responseMap;
    }

    @RequestMapping(value = "/uploadSsbpsyj",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> uploadSsbpsyj(
            @RequestParam(value = "projectid") Integer projectid,
            @RequestParam(value = "yjpath") String yjpath,
            HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Sbpsyj sbpsyj = new Sbpsyj();
        sbpsyj.setProjectid(projectid);
        sbpsyj.setYjpath(yjpath);
        User user = (User)request.getSession().getAttribute("user");
        sbpsyj.setUserid(user.getId());
        sbpsyjService.updateByPrimaryKeySelective(sbpsyj);
        responseMap.put("info", "提交成功");
        responseMap.put("success", true);
        return responseMap;
    }
    /**
     * 上传书面评审意见
     * @param request
     * @param response
     */
//    @RequestMapping(value="/uploadSsbpsyj",method= RequestMethod.POST)
//    public void uploadSsbpsyj(MultipartHttpServletRequest request,HttpServletResponse response){
//        MultipartFile file = request.getFile("file");
//        response.setContentType("text/html");
//        response.setCharacterEncoding("utf-8");
//        User user = (User)request.getSession().getAttribute("user");
//        PrintWriter out = null;
//        try{
//            Sbpsyj sbpsyj = new Sbpsyj();
//            int projectid = Integer.parseInt(request.getParameter("projectid"));
//            sbpsyj.setProjectid(projectid);
//            sbpsyj.setUserid(user.getId());
//            out = response.getWriter();
//            if(!file.isEmpty()){
//                String[] fileNameArray = file.getOriginalFilename().split("\\.");
//                if(!(fileNameArray.length>1
//                        && (fileNameArray[fileNameArray.length-1].equalsIgnoreCase("rar")
//                        || fileNameArray[fileNameArray.length-1].equalsIgnoreCase("zip")
//                        || fileNameArray[fileNameArray.length-1].equalsIgnoreCase("doc")
//                        || fileNameArray[fileNameArray.length-1].equalsIgnoreCase("docx")))){
//                    out.print("{'info':'只支持word文件和zip、rar格式的压缩文件'}");
//                    return;
//                }
//                Project project = projectService.selectByPrimaryKey(projectid);
//                String filePath = request.getSession().getServletContext().getRealPath("/") +  project.getFilepath();
//                String fileName = UUID.randomUUID() + "." + fileNameArray[fileNameArray.length-1];
//                File saveFile = new File(filePath + fileName);
//                FileUtils.writeByteArrayToFile(saveFile, file.getBytes());
//                sbpsyj.setYjpath(fileName);
//                sbpsyjService.updateByPrimaryKeySelective(sbpsyj);
//                out.print("{'success':'true'}");
//            }
//        } catch (Exception e){
//            e.printStackTrace();
//            out.print("{'info':'上传失败'}");
//        }
//    }

    /**
     * 获取申报课题审核分页
     * @param start
     * @param limit
     * @return
     */
    @RequestMapping(value = "/listForSbktsh",method= RequestMethod.POST)
    public @ResponseBody
    Map<String,Object> listForSbktsh(@RequestParam(value = "start") Integer start,
                                     @RequestParam(value = "limit") Integer limit,
                                     HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        int total = sbpsyjService.countBySbpsyj(criteria);
        criteria.setMysqlOffset(start);
        criteria.setMysqlLength(limit);
        criteria.setOrderByClause("id desc");
        criteria.put("state",1);
        criteria.put("inschool",1);
        List<Project> list = sbpsyjService.selectBySbpsyj(criteria);
        criteria.clear();
        for(Project project:list){
            List<Map> users = projectService.getUserByProjectId(project.getId());
            if(users.get(0).get("deptname")!=null){
                project.setDeptname((String) users.get(0).get("deptname"));
            }
            StringBuffer sb = new StringBuffer();
            for(Map map:users){
                if((Boolean)map.get("iscolleague")){
                    sb.append(","+map.get("username"));
                } else {
                    sb.append(",("+map.get("username")+")");
                }
            }
            project.setNames(sb.substring(1));

            criteria.put("projectid",project.getId());
            List<Sbpsyj> sbpsyjs = sbpsyjService.selectByExample(criteria);
            project.setExpertCount(sbpsyjs.size());
            for(Sbpsyj sbpsyj:sbpsyjs){
                if(sbpsyj.getIsagree()!=null){
                    if(sbpsyj.getIsagree()){
                        project.setAgreeCount(project.getAgreeCount()+1);
                    } else if(sbpsyj.getIsagree()){
                        project.setDisagreeCount(project.getDisagreeCount()+1);
                    }
                }
                if(sbpsyj.getIsleader()){
                    project.setYjpath(sbpsyj.getYjpath());
                }
            }
        }
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }
}
